<template>
  <div id="staRoleSetDiv">
    <Splitpanes>
      <Pane size="30">
        <vxe-toolbar perfect>
          <template #buttons>
            <!-- <vxe-input style="width: 180px" v-model="searchRoleForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getStaRoleList" @keyup="keyupRoleEnter" @search-click="getStaRoleList()"></vxe-input> -->
            <div class="smallToolTitle">模型</div>
            <vxe-select v-model="searchRoleForm.modelId" :filterable="true" @change="valueChangeEvent">
              <vxe-option v-for="sModel in modelList" :key="sModel.id" :value="sModel.id" :label="sModel.modelName"></vxe-option>
            </vxe-select>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addStaRoleDialog()"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteStaRole"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="roleTable">
          <vxe-table ref="staRoleTableRef" class="mytable-scrollbar staRoleTableClazz" border="inner" align="center" height="auto" :data="staRoleList" :loading="tloading" @current-change="roleRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30"></vxe-column>
            <vxe-column field="staRoleCode" title="接口编号" width="150">
              <template #default="{ row }">
                <el-link type="primary" :underline="false" @click="editStaRoleDialog(row)">
                  <span>{{row.staRoleCode}}</span>
                </el-link>
              </template>
            </vxe-column>
            <vxe-column field="roleCode" title="角色编号"></vxe-column>
            <vxe-column field="roleName" title="角色名称">
            </vxe-column>
            <vxe-column field="remark" title="描述">
            </vxe-column>
            <vxe-column field="isOpen" title="是否启用" width="50">
              <template #default="{ row }">
                <el-tag :type="getIsTagType(row.isOpen)">{{ getIsStatusDesc(row.isOpen) }}</el-tag>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <vxe-modal v-model="isRoleVisiable" width="25vw" height="35vh" show-footer :mask="false" @close="cancelRoleEvent">
          <template #title>
            <span>模型</span>
          </template>
          <template #default>
            <div class="form-panel">
              <vxe-form :data="staRoleForm" title-width="80">
                <vxe-form-item title="模型编号" span="24" field="modelCode">
                  <template #default="{ data }">
                    <vxe-input v-model="data.modelCode" placeholder="模型编号" readonly></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="接口编号" span="24" field="staRoleCode">
                  <template #default="{ data }">
                    <vxe-input v-model="data.staRoleCode" placeholder="模型编号"></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="角色编号" span="24" field="roleCode">
                  <template #default="{ data }">
                    <vxe-input v-model="data.roleCode" placeholder="模型编号"></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="角色名称" span="24" field="roleName">
                  <template #default="{ data }">
                    <vxe-input v-model="data.roleName" placeholder="模型名称"></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="描述" span="24" field="remark">
                  <template #default="{ data }">
                    <vxe-textarea v-model="data.remark" placeholder="描述"></vxe-textarea>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="是否启用" span="24" field="isOpen">
                  <template #default="{ data }">
                    <vxe-input v-model="data.isOpen" placeholder="模型名称"></vxe-input>
                  </template>
                </vxe-form-item>

              </vxe-form>
            </div>
          </template>
          <template #footer>
            <vxe-button type="text" class="button-white" @click="cancelRoleEvent">取消</vxe-button>
            <vxe-button type="text" class="button-blue" @click="confirmRoleEvent">确定</vxe-button>
          </template>
        </vxe-modal>
      </Pane>
      <Pane size="35">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">模块设定</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :disabled="disabledTag" :loading="qloading" @click="findStaModelModuleList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加" :disabled="disabledTag" @click="addModuleDialog()"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="staRoleModuleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table ref="roleModuleTableRef" :data="roleModuleList" :loading="qloading" @current-change="roleModuleRowClick" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true}" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30" align="center"></vxe-column>
            <vxe-column field="icon" title="图标" width="50">
              <template #default="{ row }">
                <el-icon size="20" class="icon">
                  <component :is="row.icon"></component>
                </el-icon>
              </template>
            </vxe-column>
            <vxe-column field="staModCode" title="标准编号" width="100">
            </vxe-column>
            <vxe-column field="modCode" title="模块编号" width="100">
            </vxe-column>
            <vxe-column field="modName" title="模块名称" width="140">
            </vxe-column>
            <vxe-column field="seq" title="顺序"> </vxe-column>
          </vxe-table>
        </div>
        <el-dialog title="模块字典" :show-close="false" v-model="showModuleDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showModuleDialog">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 130px" v-model="searchModuleForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findStaModelModuleList2" @keyup="keyupModuleEnter" @search-click="findStaModelModuleList2()"></vxe-input>
              <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="findStaModelModuleList2"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody" style="height: 600px">
            <vxe-table ref="staModelModuleTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="modelModuleList" :loading="lloading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" :checkbox-config="{
                  checkMethod: checCheckboxkMethod2,
                  visibleMethod: showCheckboxkMethod2,
                  checkRowKeys: defaultSelecteRowKeys
                }" resizable show-overflow keep-source>

              <vxe-column type="checkbox" width="30px"></vxe-column>
              <vxe-column field="icon" title="图标" width="50">
                <template #default="{ row }">
                  <el-icon size="20" class="icon">
                    <component :is="row.icon"></component>
                  </el-icon>
                </template>
              </vxe-column>
              <vxe-column field="staModCode" title="标准编号" width="100">
              </vxe-column>
              <vxe-column field="modCode" title="模块编号" width="100">
              </vxe-column>
              <vxe-column field="modName" title="模块名称" width="100">
              </vxe-column>
              <vxe-column field="bigIcon" title="大图标" width="100">
              </vxe-column>
              <vxe-column field="phone" title="背景色" width="100">
                <template #default="{ row }">
                  <span class="margin-left-xs padding-lr-xs" :style="{ background: `${row.bigIconBgcolour}` }">{{ row.bigIconBgcolour }}</span>
                </template>
              </vxe-column>
              <vxe-column field="baseUrl" title="路径">
              </vxe-column>
              <vxe-column field="seq" title="顺序" width="50">
              </vxe-column>
            </vxe-table>

            <div class="dialog-footer flex right justify-end">
              <el-button type="primary" @click="saveBacthModule('staModelModuleTableRef')">确定</el-button>
              <el-button @click="closeModuleDialog('staModelModuleTableRef')">取消</el-button>
            </div>
          </div>
        </el-dialog>
      </Pane>
      <Pane size="35">
         <StaRoleMenu ref="roleMenuRef" />
      </Pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import StaRoleMenu from './StaRoleMenu.vue';
defineExpose({ initPage });
let tloading = ref(false); //加载状态
let staRoleList: any = reactive([]);
let sltStaRole: any = ref({});
let disabledTag = ref(true); //中间质控品维护按钮标记
let isRoleVisiable = ref(false);
let modelList: any = reactive([]); //左侧仪器下拉项
let showModuleDialog = ref(false); //添加弹框展示状态
let modelModuleList: any = reactive([]); //右侧质控项目表格数据
let lloading = ref(false); //弹框表格数据加载状态
let roleModuleList: any = reactive([]);
let qloading = ref(false);
let sltRoleModule: any = ref({});
let roleMenuRef: any = ref(null);

let searchRoleForm = reactive({
  seachValue: '',
  modelId: '',
  modelCode: ''
});

let searchModuleForm = reactive({
  seachValue: ''
});

let staRoleForm = reactive({
  id: null,
  modelId: '',
  modelCode: '',
  staRoleCode: '',
  roleCode: '',
  roleName: '',
  remark: '',
  isOpen: '1',
  orgId: ''
});
function initPage() {
  findStaModelList();
}

function valueChangeEvent() {
  console.log(searchRoleForm.modelId);
  searchRoleForm.modelCode = modelList.find((a) => a.id == searchRoleForm.modelId).modelCode;
  getStaRoleList();
}

// 获取左侧仪器下拉选项数据(标题)
function findStaModelList() {
  modelList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staModel/findStaModelList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '' }
    })
    .then((res: any) => {
      modelList.push(...res.data);
      if (modelList.length > 0) {
        searchRoleForm.modelId = modelList[0].id;
        searchRoleForm.modelCode = modelList[0].modelCode;
        getStaRoleList();
      }
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

function getStaRoleList() {
  tloading.value = true;
  staRoleList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staRole/findStaRoleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchRoleForm.seachValue,
        modelId: searchRoleForm.modelId
      }
    })
    .then((res: any) => {
      staRoleList.push(...res.data);
      const kn = staRoleList.find((k) => k.id == sltStaRole.value.id);
      if (isEmpty(kn)) {
        roleRowClick({ row: staRoleList[0] }); //默认选中第一条数据
      } else {
        roleRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function editStaRoleDialog(row: any) {
  setStaRoleForm(row);
  isRoleVisiable.value = true;
}
function addStaRoleDialog() {
  staRoleForm.modelId = searchRoleForm.modelId;
  staRoleForm.modelCode = searchRoleForm.modelCode;
  isRoleVisiable.value = true;
}

// 回车查询
function keyupRoleEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getStaRoleList();
  }
}

function deleteStaRole() {
  const sltStaRoles = (proxy.$refs.staRoleTableRef as any).getCheckboxRecords();
  if (!(sltStaRoles.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delStaRoleList = sltStaRoles.filter((p: any) => !isEmpty(p.id));
        if (delStaRoleList.length > 0) {
          const data = { staRoleList: delStaRoleList };
          const url = '/lis/sta/staRole/batchDeleteStaRoleList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              getStaRoleList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function cancelRoleEvent() {
  clearStaRoleForm();
  isRoleVisiable.value = false;
}

function confirmRoleEvent() {
  if (staRoleForm.id === null) {
    const url = '/lis/sta/staRole/addStaRole';
    const staRole = {
      modelId: staRoleForm.modelId,
      modelCode: staRoleForm.modelCode,
      staRoleCode: staRoleForm.staRoleCode,
      roleCode: staRoleForm.roleCode,
      roleName: staRoleForm.roleName,
      remark: staRoleForm.remark,
      isOpen: staRoleForm.isOpen
    };
    proxy.$http
      .post(url, staRole)
      .then((res: any) => {
        VxeMessage('新增成功', VxeNotifyType.success);
        clearStaRoleForm();
        sltStaRole.value.id = res.data.id;
        getStaRoleList();
        isRoleVisiable.value = false;
      })
      .catch((err: any) => {
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    // 修改用户
    const url = '/lis/sta/staRole/editStaRole';

    const staRole = {
      id: staRoleForm.id,
      modelId: staRoleForm.modelId,
      modelCode: staRoleForm.modelCode,
      staRoleCode: staRoleForm.staRoleCode,
      roleCode: staRoleForm.roleCode,
      roleName: staRoleForm.roleName,
      remark: staRoleForm.remark,
      isOpen: staRoleForm.isOpen
    };
    proxy.$http
      .post(url, staRole)
      .then((res: any) => {
        VxeMessage('修改成功', VxeNotifyType.success);
        sltStaRole.value.id = res.data.id;
        clearStaRoleForm();
        isRoleVisiable.value = false;
        getStaRoleList();
      })
      .catch((err: any) => {
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  }
}

function roleRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearStaRoleForm();
    sltStaRole.value = {};
  } else {
    (proxy.$refs.staRoleTableRef as any).setCurrentRow(row);
    sltStaRole.value = row;
    findStaRoleModuleList();
  }
  if (!sltStaRole.value.id) {
    disabledTag.value = true;
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
    disabledTag.value = false;
  }
}

// 编辑当前行规则
function setStaRoleForm(row: any) {
  staRoleForm.id = row.id;
  staRoleForm.modelId = row.modelId;
  staRoleForm.modelCode = row.modelCode;
  staRoleForm.staRoleCode = row.staRoleCode;
  staRoleForm.roleCode = row.roleCode;
  staRoleForm.roleName = row.roleName;
  staRoleForm.isOpen = row.isOpen;
  staRoleForm.orgId = row.orgId;
  staRoleForm.remark = row.remark;
}

// 清空中间规则弹框表单
function clearStaRoleForm() {
  staRoleForm.id = null;
  staRoleForm.staRoleCode = '';
  staRoleForm.roleCode = '';
  staRoleForm.roleName = '';
  staRoleForm.remark = '';
  staRoleForm.isOpen = '1';
  staRoleForm.orgId = '';
  //   const temp: any = proxy.$refs['refCkEditor'];
  //   temp.setValue('');
}

function findStaRoleModuleList() {
  if (isEmpty(sltStaRole.value)) {
    VxeMessage('请选模型', VxeNotifyType.error);
  } else {
    qloading.value = true;
    roleModuleList.length = 0; //放入数据前清空数据
    const url = '/lis/sta/staRoleModule/findStaRoleModuleList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { staRoleId: sltStaRole.value.id }
      })
      .then((res: any) => {
        roleModuleList.push(...res.data);
        const kn = roleModuleList.find((k) => k.id == sltRoleModule.value.id);
        if (isEmpty(kn)) {
          roleModuleRowClick({ row: roleModuleList[0] }); //默认选中第一条数据
        } else {
          roleModuleRowClick({ row: kn }); //默认选中第一条数据
        }
        qloading.value = false;
      })
      .catch((err: any) => {
        qloading.value = false;
        console.log(err);
        
        VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
      });
  }
}

function roleModuleRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltRoleModule.value = {};
    roleMenuRef.value.initPage(row);
  } else {
    (proxy.$refs.roleModuleTableRef as any).setCurrentRow(row);
    sltRoleModule.value = row;
    roleMenuRef.value.initPage(row);
  }
}

// 添加按钮
function addModuleDialog() {
  if (isEmpty(sltStaRole.value)) {
    VxeMessage('请选择模型', VxeNotifyType.error);
  } else {
    findStaModelModuleList();
    showModuleDialog.value = true;
  }
}

function findStaModelModuleList() {
  lloading.value = true;
  modelModuleList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staModelModule/findStaModelModuleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchModuleForm.seachValue,
        modelId: searchRoleForm.modelId
      }
    })
    .then((res: any) => {
      modelModuleList.push(...res.data);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常2', VxeNotifyType.error);
    });
}

function findStaModelModuleList2() {
  lloading.value = true;
  modelModuleList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staModelModule/findStaModelModuleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchModuleForm.seachValue,
        modelId: searchRoleForm.modelId
      }
    })
    .then((res: any) => {
      modelModuleList.push(...res.data);

      const staModIds = roleModuleList.map((m) => m.staModId);
      const ilist = modelModuleList.filter((p: any) => staModIds.includes(p.staModId));
      console.log(ilist);
      
      const $table = proxy.$refs.staModelModuleTableRef;
      $table.setCheckboxRow(ilist, true);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常1', VxeNotifyType.error);
    });
}

// 回车查询
function keyupModuleEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findStaModelModuleList2();
  }
}

function saveBacthModule() {
  const selectRows = (proxy.$refs.staModelModuleTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addRoleModuleList = [];
    for (const sltRow of selectRows) {
      const roleModule = roleModuleList.find((qc: any) => qc.staModId == sltRow.staModId);
      if (isEmpty(roleModule)) {
        const addRoleModule = {
          staRoleId: sltStaRole.value.id,
          staRoleCode: sltStaRole.value.staRoleCode,
          modelId: sltRow.modelId,
          modelCode: sltRow.modelCode,
          staModId: sltRow.staModId,
          staModCode: sltRow.staModCode,
          seq: sltRow.seq
        };
        addRoleModuleList.push(addRoleModule);
      }
    }
    if (addRoleModuleList.length > 0) {
      const data = { staRoleModuleList: addRoleModuleList };
      const url = '/lis/sta/staRoleModule/batchAddStaRoleModuleList';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          findStaRoleModuleList(); // 获取检验仪器表格数据
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      VxeMessage('请选择要添加的数据', VxeNotifyType.error);
    }
  }
  closeModuleDialog();
}

// 弹框取消按钮
function closeModuleDialog() {
  searchModuleForm.seachValue = '';
  defaultSelecteRowKeys.length = 0;
  showModuleDialog.value = false;
}

function staRoleModuleDelete() {
  const sltRoleModules = (proxy.$refs.roleModuleTableRef as any).getCheckboxRecords();
  if (!(sltRoleModules.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { staRoleModuleList: sltRoleModules };
        const url = '/lis/sta/staRoleModule/batchDeleteStaRoleModuleList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findStaRoleModuleList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

let defaultSelecteRowKeys = reactive([]);
// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  const obj = roleModuleList.filter((p: any) => {
    if(p.staModId == row.staModId){
    defaultSelecteRowKeys.push(row.id);

    }
    return p.staModId == row.staModId;
  });
  return obj.length == 0;
}

// 弹框 表格复选框 设置(是否显示复选框)
function showCheckboxkMethod2({ row }: any) {
  const obj = roleModuleList.filter((p: any) => {});
  return obj.length == 0;
}

function getIsTagType(row: any) {
  if (row == '1') {
    return 'success';
  } else {
    return 'danger';
  }
}
// 获取是否静态文字(是/否)
function getIsStatusDesc(row: any) {
  if (row == '1') {
    return '是';
  } else {
    return '否';
  }
}
</script>

<style lang="scss" scoped>
#staRoleSetDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .roleTable {
    height: calc(100% - 40px);
    background-color: $base-white;
  }

  .tableBox {
    height: calc(100% - 40px);
  }
}
</style>
